package com.netty.action.transport;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.oio.OioServerSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * 用netty blocking Io做服务端
 */
public class NettyOioServer {


    public void server(int port) throws Exception {
        final ByteBuf buf = Unpooled.unreleasableBuffer(
                Unpooled.copiedBuffer("Hi! I'm Netty Blocking Io Message\r\n", CharsetUtil.UTF_8));
        EventLoopGroup group = new OioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();// 1 建立服务端serverBootstrap

            b.group(group) //2使用 NioEventLoopGroup 允许非阻塞模式（NIO）
                    .channel(OioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {//3 指定 ChannelInitializer 将给每个接受的连接调用
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {//4 添加的 ChannelHandler 拦截事件，并允许他们作出反应
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    //5 写信息到客户端，并添加 ChannelFutureListener 当一旦消息写入就关闭连接
                                    // 这里对 ChannelFutureListener.CLOSE 改成了 ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE
                                    // 主要是方便测试，否则客户还没有来得及接收消息就会会报异常说，服务端主动断开连接，
                                    // 改成下面这样，只有出现异常才会关闭联接
                                    ctx.writeAndFlush(buf.duplicate()).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
                                }
                            });
                        }
                    });
            ChannelFuture f = b.bind().sync();  //6 绑定服务器来接受连接
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync(); //7 释放所有资源
        }
    }

    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        new NettyOioServer().server(4200);
    }
}
